import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { SET_ROUTES, SET_SUB_NAV_LIST, SET_MENUS } from '../constants';

const initalState = {
  routes: [],
  subNavList: {},
  menus: {
    title: '',
    data: [],
  },
};

export function setRoutes(routes) {
  return {
    type: SET_ROUTES,
    routes,
  };
}
export function useRoutes() {
  const dispatch = useDispatch();
  const routes = useSelector((state) => state.user.routes);
  const boundAction = useCallback((routes) => dispatch(setRoutes(routes)), [dispatch]);
  return { routes, setRoutes: boundAction };
}
export function routes(state = initalState, action) {
  switch (action.type) {
    case SET_ROUTES:
      return {
        ...state,
        routes: action.routes,
      };
    default:
      break;
  }
  return state;
}

// subNavList
export function setSubNavList(subNavList) {
  return {
    type: SET_SUB_NAV_LIST,
    subNavList,
  };
}
export function useSubNavList() {
  const dispatch = useDispatch();
  const subNavList = useSelector((state) => state.user.subNavList);
  const boundAction = useCallback((subNavList) => dispatch(setSubNavList(subNavList)), [dispatch]);
  return { subNavList, setSubNavList: boundAction };
}
export function subNavList(state, action) {
  switch (action.type) {
    case SET_SUB_NAV_LIST:
      return {
        ...state,
        subNavList: action.subNavList,
      };
    default:
      break;
  }
  return state;
}

// menus
export function setmenus(menus) {
  return {
    type: SET_MENUS,
    menus,
  };
}
export function useMenus() {
  const dispatch = useDispatch();
  const menus = useSelector((state) => state.user.menus);
  const boundAction = useCallback((menus) => dispatch(setmenus(menus)), [dispatch]);
  return { menus, setmenus: boundAction };
}
export function menus(state, action) {
  switch (action.type) {
    case SET_MENUS:
      return {
        ...state,
        menus: action.menus,
      };
    default:
      break;
  }
  return state;
}

const reducers = [routes, subNavList, menus];

export default function reducer(state = initalState, action) {
  let newState;
  switch (action.type) {
    // Handle cross-topic actions here
    default:
      newState = state;
      break;
  }
  return reducers.reduce((s, r) => r(s, action), newState);
}
